<template>
  <div class="add_goods">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-alert center title="添加商品信息" type="info" show-icon :closable="false"></el-alert>
      <el-steps align-center :active="+step_active" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成" name='5'></el-step>
      </el-steps>
      
      <el-form ref="baseInfoFormRef" :model="baseInfoForm" :rules="baseInfoRules">
        <el-tabs tab-position="left" v-model="step_active" :before-leave="beforeTabLeave" @tab-click="tabClicked">
          <el-tab-pane label="基本信息" name='0'>
            <el-form-item label="商品名称" prop='goods_name'>
              <el-input v-model="baseInfoForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop='goods_price'>
              <el-input type="number" v-model="baseInfoForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop='goods_weight'>
              <el-input type="number" v-model="baseInfoForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop='goods_number'>
              <el-input type="number" v-model="baseInfoForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <br>
              <el-cascader
                v-model="baseInfoForm.goods_cat"
                :options="cascade_options"
                :props="cascade_props"
                @change="handleCascadeChange">
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name='1'>
            <el-form-item :label="item.attr_name" v-for="(item,index) in many_list" :key="index">
              <br>
              <el-checkbox-group  v-model="item.attr_vals">
                <el-checkbox border v-for="(subitem,subindex) in item.attr_vals" :key="subindex" :label="subitem"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name='2'>
            <el-form-item :label="item.attr_name" v-for="(item,index) in only_list" :key="index">
              <el-input v-model="item.attr_vals" placeholder="请输入商品属性"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name='3'>
            <el-upload
              class="upload-demo"
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="successUpload"
              :headers="headers"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name='4'>
            <quill-editor
              ref="myQuillEditor"
              v-model="baseInfoForm.goods_introduce"
              :options="editorOption"
              @blur="onEditorBlur($event)"
              @focus="onEditorFocus($event)"
              @ready="onEditorReady($event)"
            >
            </quill-editor>
            <el-button type="primary" class="add_goods" @click="confirmAddGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 预览图片的弹窗 -->
    <el-dialog
      title=""
      :visible.sync="previewDialogVisible"
      width="50%">
      <img :src="previewURL" width="100%">
    </el-dialog>
  </div>
</template>

<script>
export default{
  data(){
    return {
      step_active:'0',
      baseInfoRules:{
          goods_name: [
            { required: true, message: '请输入商品名称', trigger: 'blur' },
            { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
          ],
          goods_price: [
            { required: true, message: '请输入商品价格', trigger: 'blur' },
          ],
          goods_weight: [
            { required: true, message: '请输入商品重量', trigger: 'blur' },
          ],
          goods_number: [
            { required: true, message: '请输入商品数量', trigger: 'blur' },
          ],
          goods_cat: [
            { required: true, message: '请选择商品分类', trigger: 'blur' },
          ]
      },
      baseInfoForm:{
        goods_name:'',
        goods_price:'',
        goods_number:'',
        goods_weight:'',
        goods_cat:[] ,//级联选择器当前选择的值
        pics:[],
        goods_introduce:'',
        attrs:[]
      },
      cascade_options:[],//级联选择器的数据
      cascade_props:{
        label:'cat_name',
        value:'cat_id',
        children:'children',
        expandTrigger: 'hover'
      },//级联选择器配置
      many_list:[],//动态参数的数组
      only_list:[],//静态属性的数组
      headers:{
        Authorization:window.sessionStorage.getItem('token')
      },
      previewDialogVisible:false,
      previewURL:'',//图片预览使用的地址
      editorOption:{}
    }
  },
  created(){
    this.initCascade()
  },
  computed:{
    cateId(){
      if(this.baseInfoForm.goods_cat.length===3){
        return this.baseInfoForm.goods_cat[2]
      }
    }
  },
  methods:{
    //初始化级联选择器数据
    async initCascade(){
      const res=await this.$http.get('categories')
      if(res.data.meta.status!==200) return this.$message.error('获取商品分类失败')
      this.cascade_options=res.data.data
      // console.log(res);
    },
    //级联选择器改变
    handleCascadeChange(){
      // console.log(this.baseInfoForm.goods_cat);
      if(this.baseInfoForm.goods_cat.length!==3){
        this.baseInfoForm.goods_cat=[]
      }
      console.log(this.baseInfoForm.goods_cat);
    },
    //监听tab栏切换之前
    beforeTabLeave(active,old){
      // console.log(active,old);
      //判断从index0离开时是否选择了商品分类
      if(old === '0' && this.baseInfoForm.goods_cat.length!==3){
        this.$message.error('请先选择商品分类')
        return false
      }
    },
    async tabClicked(){
      // console.log(this.step_active);
      if(this.step_active==='1'){
        const res=await this.$http.get(`categories/${this.cateId}/attributes`,{params:{sel:'many'}})
        if(res.data.meta.status!==200) return this.$message.error('获取数据失败')
        res.data.data.forEach(item => {
          item.attr_vals=item.attr_vals==''?[]:item.attr_vals.split(' ')
        });
        this.many_list=res.data.data
        console.log(this.many_list);
      }else if(this.step_active ==='2'){
        const res=await this.$http.get(`categories/${this.cateId}/attributes`,{params:{
          sel:'only'
        }})
        if(res.data.meta.status!==200) return this.$message.error('获取数据失败')
        this.only_list=res.data.data
      }
    },
    //图片上传成功后的回调
    successUpload(res){
      this.baseInfoForm.pics.push({'pic':res.data.tmp_path})
      // console.log(this.baseInfoForm);
    },
    //图片预览
    handlePreview(file){
      console.log(file);
      this.previewURL=file.response.data.url
      this.previewDialogVisible=true
    },
    //图片移除
    handleRemove(file){
      // console.log(file);
      const tempath=file.response.tmp_path
      const index=this.baseInfoForm.pics.findIndex(item=>{
        item = tempath
      })
      this.baseInfoForm.pics.splice(index,1)
      console.log(this.baseInfoForm);
    },
    //提交添加
    confirmAddGoods(){
      this.$refs.baseInfoFormRef.validate(async valid=>{
        if(!valid) return this.$message.error('请输入必填的表单项')
        // console.log('校验通过');
        this.baseInfoForm.goods_cat=this.baseInfoForm.goods_cat.join(',')
        // console.log(this.baseInfoForm);
        const form = []
        this.many_list.forEach(item => {
          form.push({
            attr_id:item.attr_id,
            attr_value:item.attr_vals.join(',')
          })
        });
        this.only_list.forEach(item => {
          form.push({
            attr_id:item.attr_id,
            attr_value:item.attr_vals
          })
        });
        this.baseInfoForm.attrs=form
        console.log(this.baseInfoForm);
        const res=await this.$http.post('goods',this.baseInfoForm)
        console.log(res);
        if(res.data.meta.status!==201) return this.$message.error('创建商品失败')
        this.$message.success('创建商品成功')
        this.$router.push('/goods')
      })
    },
    onEditorBlur(e){

    },
    onEditorFocus(e){

    },
    onEditorReady(e){

    }
  }
}
</script>

<style lang="less" scoped>
.add_goods{
  .el-card{
    margin-top: 20px;
    .el-steps{
      width: 80%;
      margin: 20px auto ;
    }
    .el-form{
      .el-input{
        margin-top: 15px;
      }
    }
    .el-checkbox{
      margin: 0 5px 0 0 !important;
    }
    .add_goods{
      margin-top: 20px;
    }
  }
}
</style>